import Vue from 'vue'
import Vuex from 'vuex'
import { Toast } from 'vant'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    _list: localStorage.getItem('items')
      ? JSON.parse(localStorage.getItem('items'))
      : []
  },
  getters: {
    count: function (state) {
      return state._list.length
    }
  },
  mutations: {
    addnum (state, items) {
      console.log('11')
      console.log(items)
      if (!localStorage.getItem('items')) {
        items.value = 1
        items.checked = true
        state._list.push(items)
        Toast.success('物品已添加至购物车')
      } else {
        const arritem = JSON.parse(localStorage.getItem('items'))
        const bollen = arritem.every(elem => {
          if (elem.id === items.id) {
            return false
          } else {
            return true
          }
        })
        if (bollen) {
          items.value = 1
          items.checked = true
          state._list = JSON.parse(localStorage.getItem('items'))
          state._list.push(items)
          Toast.success('物品已添加至购物车')
        } else {
          Toast.fail('物品已存在')
        }
      }
      console.log(state._list)
      localStorage.setItem('items', JSON.stringify(state._list))
    },
    getlist (state) {
      state._list = JSON.parse(localStorage.getItem('items'))
    }
  },
  actions: {
    insert_cart ({ commit }, num) {
      commit('addnum', num)
    },
    set_cart ({ commit }) {
      commit('getlist')
    }
  }
})
